

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" href="/img/favicon.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="Han Qiu">
  <meta name="keywords" content="">
  
    <meta name="description" content="0、HTTP协议 HTTP 超文本传输协议，协议详细规定了浏览器与万维网服务器之间互相通信的规则。  请求报文：  响应报文：   1、Ajax简介 Ajax全称为Asynchronous JavaScript And XML，就是异步的JS和XML 通过Ajax可以在浏览器中向服务器发送异步请求，最大的优势：无刷新获取数据 Ajax不是新的编程语言，而是一种将现有的标准组合在一起使用的新方式">
<meta property="og:type" content="article">
<meta property="og:title" content="ajax基础">
<meta property="og:url" content="http://example.com/2022/01/06/ajax%E5%9F%BA%E7%A1%80/index.html">
<meta property="og:site_name" content="寒秋の博客">
<meta property="og:description" content="0、HTTP协议 HTTP 超文本传输协议，协议详细规定了浏览器与万维网服务器之间互相通信的规则。  请求报文：  响应报文：   1、Ajax简介 Ajax全称为Asynchronous JavaScript And XML，就是异步的JS和XML 通过Ajax可以在浏览器中向服务器发送异步请求，最大的优势：无刷新获取数据 Ajax不是新的编程语言，而是一种将现有的标准组合在一起使用的新方式">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/huqian025/my-images/raw/master/ajax/ajax%E5%9F%BA%E7%A1%80/%E8%AF%B7%E6%B1%82%E6%8A%A5%E6%96%87.png">
<meta property="og:image" content="https://gitee.com/huqian025/my-images/raw/master/ajax/ajax%E5%9F%BA%E7%A1%80/%E5%93%8D%E5%BA%94%E6%8A%A5%E6%96%87.png">
<meta property="og:image" content="https://gitee.com/huqian025/my-images/raw/master/ajax/ajax%E5%9F%BA%E7%A1%80/%E8%A7%A3%E5%86%B3%E8%B7%A8%E5%9F%9F.png">
<meta property="article:published_time" content="2022-01-06T03:14:25.000Z">
<meta property="article:modified_time" content="2022-01-06T03:47:41.777Z">
<meta property="article:author" content="Han Qiu">
<meta property="article:tag" content="ajax">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://gitee.com/huqian025/my-images/raw/master/ajax/ajax%E5%9F%BA%E7%A1%80/%E8%AF%B7%E6%B1%82%E6%8A%A5%E6%96%87.png">
  
  
  <title>ajax基础 - 寒秋の博客</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4/github-markdown.min.css" />
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hint.css@2/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10/styles/github-gist.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.css" />
  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.8.14","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 6.0.0"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>blogs</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('/img/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="ajax基础">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2022-01-06 11:14" pubdate>
        2022年1月6日 上午
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      4.6k 字
    </span>
  

  
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      39 分钟
    </span>
  

  
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">ajax基础</h1>
            
            <div class="markdown-body">
              <h4 id="0、HTTP协议"><a href="#0、HTTP协议" class="headerlink" title="0、HTTP协议"></a>0、HTTP协议</h4><ul>
<li><p>HTTP 超文本传输协议，协议详细规定了浏览器与万维网服务器之间互相通信的规则。</p>
</li>
<li><p>请求报文：<br><img src="https://gitee.com/huqian025/my-images/raw/master/ajax/ajax%E5%9F%BA%E7%A1%80/%E8%AF%B7%E6%B1%82%E6%8A%A5%E6%96%87.png" srcset="/img/loading.gif" lazyload alt="请求报文"></p>
</li>
<li><p>响应报文：<br><img src="https://gitee.com/huqian025/my-images/raw/master/ajax/ajax%E5%9F%BA%E7%A1%80/%E5%93%8D%E5%BA%94%E6%8A%A5%E6%96%87.png" srcset="/img/loading.gif" lazyload alt="响应报文"></p>
</li>
</ul>
<h4 id="1、Ajax简介"><a href="#1、Ajax简介" class="headerlink" title="1、Ajax简介"></a>1、Ajax简介</h4><ul>
<li>Ajax全称为Asynchronous JavaScript And XML，就是异步的JS和XML</li>
<li>通过Ajax可以在浏览器中向服务器发送异步请求，最大的优势：<strong>无刷新获取数据</strong></li>
<li>Ajax不是新的编程语言，而是一种将现有的标准组合在一起使用的新方式</li>
</ul>
<h4 id="2、XML简介"><a href="#2、XML简介" class="headerlink" title="2、XML简介"></a>2、XML简介</h4><ul>
<li>XML可扩展标记语言，被设计用来传输和存储数据</li>
<li>XML和HTML类似，不同的是HTML中都是预定义标签，而XML中没有预定义标签，全部都是自定义标签，用来表示一些数据</li>
</ul>
<figure class="highlight xml"><table><tr><td class="gutter"><div class="code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></div></td><td class="code"><pre><code class="hljs xml"><span class="hljs-comment">&lt;!-- 例如：有一个学生数据name=&quot;孙悟空&quot;; age=18; gender=&quot;男&quot; --&gt;</span><br><span class="hljs-comment">&lt;!-- 用XML表示： --&gt;</span><br><span class="hljs-tag">&lt;<span class="hljs-name">student</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">name</span>&gt;</span>孙悟空<span class="hljs-tag">&lt;/<span class="hljs-name">name</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">age</span>&gt;</span>18<span class="hljs-tag">&lt;/<span class="hljs-name">age</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">gender</span>&gt;</span>男<span class="hljs-tag">&lt;/<span class="hljs-name">gender</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">student</span>&gt;</span><br></code></pre></td></tr></table></figure>

<ul>
<li>现在已经被JSON取代了<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs json"><span class="hljs-comment">// 用JSON表示：</span><br>&#123;<br>    <span class="hljs-attr">&quot;name&quot;</span>: <span class="hljs-string">&quot;孙悟空&quot;</span>,<br>    <span class="hljs-attr">&quot;age&quot;</span>: <span class="hljs-number">18</span>,<br>    <span class="hljs-attr">&quot;gender&quot;</span>: <span class="hljs-string">&quot;男&quot;</span><br>&#125;<br></code></pre></td></tr></table></figure></li>
</ul>
<h4 id="3、Ajax特点"><a href="#3、Ajax特点" class="headerlink" title="3、Ajax特点"></a>3、Ajax特点</h4><h5 id="3-1、Ajax优点"><a href="#3-1、Ajax优点" class="headerlink" title="3.1、Ajax优点"></a>3.1、Ajax优点</h5><ul>
<li>可以在无需刷新页面与服务器进行通信</li>
<li>允许根据用户事件来更新部分页面内容</li>
</ul>
<h5 id="3-2、Ajax缺点"><a href="#3-2、Ajax缺点" class="headerlink" title="3.2、Ajax缺点"></a>3.2、Ajax缺点</h5><ul>
<li>没有浏览历史，不能回退</li>
<li>存在跨域问题</li>
<li>SEO优化不友好</li>
</ul>
<h4 id="4、发送ajax请求"><a href="#4、发送ajax请求" class="headerlink" title="4、发送ajax请求"></a>4、发送ajax请求</h4><h5 id="4-1、原生ajax"><a href="#4-1、原生ajax" class="headerlink" title="4.1、原生ajax"></a>4.1、原生ajax</h5><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-comment">// 获取button元素</span><br><span class="hljs-keyword">const</span> btn = <span class="hljs-built_in">document</span>.getElementsByTagName(<span class="hljs-string">&#x27;button&#x27;</span>)[<span class="hljs-number">0</span>]<br><span class="hljs-keyword">const</span> box = <span class="hljs-built_in">document</span>.getElementsByClassName(<span class="hljs-string">&#x27;box&#x27;</span>)[<span class="hljs-number">0</span>]<br><span class="hljs-comment">// 绑定事件</span><br>btn.onclick = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>)</span>&#123;<br>    <span class="hljs-comment">// 1. 创建对象</span><br>    <span class="hljs-keyword">const</span> xhr = <span class="hljs-keyword">new</span> XMLHttpRequest()<br>    <span class="hljs-comment">// 2. 初始化 设置请求类型和url</span><br>    xhr.open(<span class="hljs-string">&#x27;GET&#x27;</span>, <span class="hljs-string">&#x27;http://127.0.0.1:8000/server&#x27;</span>)<br>    <span class="hljs-comment">// 3. 发送</span><br>    xhr.send()<br>    <span class="hljs-comment">// 4. 事件绑定 处理服务端返回的结果</span><br>    <span class="hljs-comment">// on when 当...时候</span><br>    <span class="hljs-comment">// readystate 是xhr对象中的属性，表示状态0,1,2,3,4（分别对应未初始化，open方法调用完毕，send方法调用完毕，服务端返回部分结果，服务端返回所有结果）</span><br>    <span class="hljs-comment">// change 改变</span><br>    xhr.onreadystatechange = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>&#123;<br>      <span class="hljs-comment">// 判断服务端返回所有结果</span><br>      <span class="hljs-keyword">if</span>(xhr.readyState === <span class="hljs-number">4</span>)&#123;<br>        <span class="hljs-comment">// 判断相应状态码，2开头都是成功</span><br>        <span class="hljs-keyword">if</span>(xhr.status &gt;= <span class="hljs-number">200</span> &amp;&amp; xhr.status &lt; <span class="hljs-number">300</span>)&#123;<br>          <span class="hljs-comment">// 处理结果</span><br>          <span class="hljs-built_in">console</span>.log(xhr.status) <span class="hljs-comment">// 响应状态码</span><br>          <span class="hljs-built_in">console</span>.log(xhr.statusText) <span class="hljs-comment">// 响应状态字符串</span><br>          <span class="hljs-built_in">console</span>.log(xhr.getAllResponseHeaders()) <span class="hljs-comment">// 所有响应头</span><br>          <span class="hljs-built_in">console</span>.log(xhr.response) <span class="hljs-comment">// 响应体</span><br>          box.innerHTML = xhr.response<br>        &#125;<br>      &#125;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<h5 id="4-2、jquery发送ajax请求"><a href="#4-2、jquery发送ajax请求" class="headerlink" title="4.2、jquery发送ajax请求"></a>4.2、jquery发送ajax请求</h5><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><code class="hljs javascript">$(<span class="hljs-string">&#x27;button&#x27;</span>).eq(<span class="hljs-number">0</span>).click(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>&#123;<br>    $.get(<span class="hljs-string">&#x27;http://127.0.0.1:8000/jquery-server&#x27;</span>, &#123; <span class="hljs-attr">a</span>: <span class="hljs-number">100</span>, <span class="hljs-attr">b</span>: <span class="hljs-number">200</span>&#125;, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">data</span>)</span>&#123;<br>      <span class="hljs-built_in">console</span>.log(data)<br>    &#125;, <span class="hljs-string">&#x27;json&#x27;</span>)<br>  &#125;)<br>  $(<span class="hljs-string">&#x27;button&#x27;</span>).eq(<span class="hljs-number">1</span>).click(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>&#123;<br>    $.post(<span class="hljs-string">&#x27;http://127.0.0.1:8000/jquery-server&#x27;</span>, &#123; <span class="hljs-attr">a</span>: <span class="hljs-number">100</span>, <span class="hljs-attr">b</span>: <span class="hljs-number">200</span>&#125;, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">data</span>)</span>&#123;<br>      <span class="hljs-built_in">console</span>.log(data)<br>    &#125;)<br>  &#125;)<br>  $(<span class="hljs-string">&#x27;button&#x27;</span>).eq(<span class="hljs-number">2</span>).click(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>&#123;<br>    $.ajax(&#123;<br>      <span class="hljs-comment">// url</span><br>      <span class="hljs-attr">url</span>: <span class="hljs-string">&#x27;http://127.0.0.1:8000/jquery-server&#x27;</span>,<br>      <span class="hljs-comment">// 参数</span><br>      <span class="hljs-attr">data</span>: &#123; <span class="hljs-attr">a</span>: <span class="hljs-number">100</span>, <span class="hljs-attr">b</span>: <span class="hljs-number">200</span>&#125;,<br>      <span class="hljs-comment">// 请求类型</span><br>      <span class="hljs-attr">type</span>: <span class="hljs-string">&#x27;GET&#x27;</span>,<br>      <span class="hljs-comment">// 响应体结果</span><br>      <span class="hljs-attr">dataType</span>: <span class="hljs-string">&#x27;json&#x27;</span>,<br>      <span class="hljs-comment">// 成功回调</span><br>      <span class="hljs-attr">success</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">data</span>)</span>&#123;<br>        <span class="hljs-built_in">console</span>.log(data)<br>      &#125;,<br>      <span class="hljs-comment">// 超时时间</span><br>      <span class="hljs-attr">timeout</span>: <span class="hljs-number">2000</span>,<br>      <span class="hljs-comment">// 失败回调</span><br>      <span class="hljs-attr">error</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>&#123;<br>        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">&#x27;出错了&#x27;</span>)<br>      &#125;<br>    &#125;)<br>  &#125;)<br></code></pre></td></tr></table></figure>

<h5 id="4-3、axios发送ajax请求"><a href="#4-3、axios发送ajax请求" class="headerlink" title="4.3、axios发送ajax请求"></a>4.3、axios发送ajax请求</h5><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">const</span> btns = <span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">&#x27;button&#x27;</span>)<br>  <span class="hljs-comment">// 配置baseURL</span><br>  axios.defaults.baseURL = <span class="hljs-string">&#x27;http://127.0.0.1:8000&#x27;</span><br>  btns[<span class="hljs-number">0</span>].onclick = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>&#123;<br>    <span class="hljs-comment">// GET请求</span><br>    axios.get(<span class="hljs-string">&#x27;axios-server&#x27;</span>, &#123;<br>      <span class="hljs-comment">// url参数</span><br>      <span class="hljs-attr">params</span>: &#123;<br>        <span class="hljs-attr">id</span>: <span class="hljs-number">100</span>,<br>        <span class="hljs-attr">vip</span>: <span class="hljs-number">7</span><br>      &#125;,<br>      <span class="hljs-comment">// 请求头信息</span><br>      <span class="hljs-attr">headers</span>: &#123;<br>        <span class="hljs-attr">name</span>: <span class="hljs-string">&#x27;abc&#x27;</span>,<br>        <span class="hljs-attr">age</span>: <span class="hljs-number">18</span><br>      &#125;<br>    &#125;).then(<span class="hljs-function"><span class="hljs-params">res</span> =&gt;</span> &#123;<br>      <span class="hljs-built_in">console</span>.log(res)<br>    &#125;)<br>  &#125;<br>  btns[<span class="hljs-number">1</span>].onclick = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>&#123;<br>    <span class="hljs-comment">// POST请求</span><br>    axios.post(<span class="hljs-string">&#x27;axios-server&#x27;</span>, <br>      &#123;<br>        <span class="hljs-comment">// 请求体</span><br>        <span class="hljs-attr">username</span>: <span class="hljs-string">&#x27;admin&#x27;</span>,<br>        <span class="hljs-attr">password</span>: <span class="hljs-string">&#x27;admin&#x27;</span><br>      &#125;, <br>      &#123;<br>        <span class="hljs-comment">// url参数</span><br>        <span class="hljs-attr">params</span>: &#123;<br>          <span class="hljs-attr">id</span>: <span class="hljs-number">100</span>,<br>          <span class="hljs-attr">vip</span>: <span class="hljs-number">7</span><br>        &#125;,<br>        <span class="hljs-comment">// 请求头信息</span><br>        <span class="hljs-attr">headers</span>: &#123;<br>          <span class="hljs-attr">name</span>: <span class="hljs-string">&#x27;abc&#x27;</span>,<br>          <span class="hljs-attr">age</span>: <span class="hljs-number">18</span><br>        &#125;<br>      &#125;<br>    ).then(<span class="hljs-function"><span class="hljs-params">res</span> =&gt;</span> &#123;<br>      <span class="hljs-built_in">console</span>.log(res)<br>    &#125;)<br>  &#125;<br>  btns[<span class="hljs-number">2</span>].onclick = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>&#123;<br>    axios(&#123;<br>      <span class="hljs-comment">// 请求类型</span><br>      <span class="hljs-attr">method</span>: <span class="hljs-string">&#x27;POST&#x27;</span>,<br>      <span class="hljs-comment">// url</span><br>      <span class="hljs-attr">url</span>: <span class="hljs-string">&#x27;axios-server&#x27;</span>,<br>      <span class="hljs-comment">// url参数</span><br>      <span class="hljs-attr">params</span>: &#123;<br>        <span class="hljs-attr">id</span>: <span class="hljs-number">100</span>,<br>        <span class="hljs-attr">vip</span>: <span class="hljs-number">7</span><br>      &#125;,<br>      <span class="hljs-comment">// 请求头信息</span><br>      <span class="hljs-attr">headers</span>: &#123;<br>        <span class="hljs-attr">name</span>: <span class="hljs-string">&#x27;abc&#x27;</span>,<br>        <span class="hljs-attr">age</span>: <span class="hljs-number">18</span><br>      &#125;,<br>      <span class="hljs-comment">// 请求体</span><br>      <span class="hljs-attr">data</span>: &#123;<br>        <span class="hljs-attr">username</span>: <span class="hljs-string">&#x27;admin&#x27;</span>,<br>        <span class="hljs-attr">password</span>: <span class="hljs-string">&#x27;admin&#x27;</span><br>      &#125;<br>    &#125;).then(<span class="hljs-function"><span class="hljs-params">res</span> =&gt;</span> &#123;<br>      <span class="hljs-built_in">console</span>.log(res)<br>    &#125;)<br>  &#125;<br></code></pre></td></tr></table></figure>

<h5 id="4-4、fetch发送ajax请求"><a href="#4-4、fetch发送ajax请求" class="headerlink" title="4.4、fetch发送ajax请求"></a>4.4、fetch发送ajax请求</h5><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">const</span> btn = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">&#x27;button&#x27;</span>)<br>  btn.onclick = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>&#123;<br>    fetch(<span class="hljs-string">&#x27;http://127.0.0.1:8000/fetch-server&#x27;</span>, &#123;<br>      <span class="hljs-comment">// 请求类型</span><br>      <span class="hljs-attr">method</span>: <span class="hljs-string">&#x27;POST&#x27;</span>,<br>      <span class="hljs-comment">// 请求头</span><br>      <span class="hljs-attr">headers</span>: &#123;<br>        <span class="hljs-attr">name</span>: <span class="hljs-string">&#x27;abc&#x27;</span><br>      &#125;,<br>      <span class="hljs-comment">// 请求体</span><br>      <span class="hljs-attr">body</span>: <span class="hljs-string">&#x27;username=admin&amp;password=admin&#x27;</span><br>    &#125;).then(<span class="hljs-function"><span class="hljs-params">res</span> =&gt;</span> &#123;<br>      <span class="hljs-comment">// console.log(res)</span><br>      <span class="hljs-keyword">return</span> res.json()<br>    &#125;).then(<span class="hljs-function"><span class="hljs-params">res</span> =&gt;</span> &#123;<br>      <span class="hljs-built_in">console</span>.log(res)<br>    &#125;)<br>  &#125;<br></code></pre></td></tr></table></figure>

<h4 id="5、跨域"><a href="#5、跨域" class="headerlink" title="5、跨域"></a>5、跨域</h4><h5 id="5-1、同源策略"><a href="#5-1、同源策略" class="headerlink" title="5.1、同源策略"></a>5.1、同源策略</h5><ul>
<li><ol>
<li>同源策略是浏览器的一种安全策略</li>
</ol>
</li>
<li><ol start="2">
<li>同源：协议、域名、端口号必须完全相同</li>
</ol>
</li>
<li><ol start="3">
<li>违背同源策略就是跨域</li>
</ol>
</li>
</ul>
<h5 id="5-2、解决跨域-jsonp"><a href="#5-2、解决跨域-jsonp" class="headerlink" title="5.2、解决跨域-jsonp"></a>5.2、解决跨域-jsonp</h5><ul>
<li><ol>
<li>jsonp是什么：jsonp是一个非官方的跨域解决方案，凭借程序员的聪明才智开发出来，只支持get请求</li>
</ol>
</li>
<li><ol start="2">
<li>jsonp怎么工作的：在网页中有一些标签天生具有跨域能力，比如img、link、iframe和script。jsonp就是利用script标签的跨域能力来发送请求的</li>
</ol>
</li>
<li><ol start="3">
<li>jsonp的使用：</li>
</ol>
<ul>
<li>1）动态创建一个script标签<code>var script = document.createElement(&#39;script&#39;)</code></li>
<li>2）设置script的src属性，设置回调函数<code>script.src = &#39;http://127.0.0.1:8000/check-username&#39;</code></li>
<li>3）将script标签插入到文档中<code>document.body.appendChild(script)</code></li>
</ul>
</li>
</ul>
<h5 id="5-3、解决跨域-设置CORS响应头"><a href="#5-3、解决跨域-设置CORS响应头" class="headerlink" title="5.3、解决跨域-设置CORS响应头"></a>5.3、解决跨域-设置CORS响应头</h5><ul>
<li><ol>
<li>CORS是什么：跨域资源共享，CORS是官方的跨域解决方案，它的特点是不需要在客户端做任何特殊的操作，完全在服务器中进行处理，支持post和get请求。跨域资源共享标准新增了一组HTTP首部字段，允许服务器声明哪些源站通过浏览器访问哪些资源</li>
</ol>
</li>
<li><ol start="2">
<li>CORS是怎么工作的：CORS是通过设置一个响应头来告诉浏览器，该请求允许跨域，浏览器收到该响应以后就会对响应放行</li>
</ol>
</li>
<li><ol start="3">
<li>CORS的使用：</li>
</ol>
<ul>
<li>在服务端设置请求的响应头<code>response.setHeader(&#39;Access-Control-Allow-Origin&#39;, &#39;*&#39;)</code></li>
</ul>
</li>
</ul>
<p><img src="https://gitee.com/huqian025/my-images/raw/master/ajax/ajax%E5%9F%BA%E7%A1%80/%E8%A7%A3%E5%86%B3%E8%B7%A8%E5%9F%9F.png" srcset="/img/loading.gif" lazyload alt="解决跨域"></p>

            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/ajax/">ajax</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/ajax/">ajax</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">
                  
                    本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！
                  
                </p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2022/01/06/js%E6%A8%A1%E5%9D%97%E5%8C%96%E8%A7%84%E8%8C%83/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">js模块化规范</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
     <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
  </div>
  

  

  
</footer>


  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  <script  src="/js/local-search.js" ></script>



  
    <script  src="/js/img-lazyload.js" ></script>
  



  



  
    <script  src="https://cdn.jsdelivr.net/npm/tocbot@4/dist/tocbot.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4/anchor.min.js" ></script>
  
  
    <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js" ></script>
  






  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
        typing(title);
      
    })(window, document);
  </script>















<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>


</body>
</html>
